import importlib
import log

Window = None   # 主窗体


def initModule(paths):
    window = Window
    for each in paths:
        print(each)
        try:
            model = importlib.import_module(each)  # 根据"auth.my_auth"导入my_auth模块
        except Exception as err:
            print('模块导入错误;', err)
            log.error('model \'', each, '\' error ', err)
        else:
            log.msg('load ', each, ' success')
            if hasattr(model, 'init'):
                model.init(window)
            else:
                log.warn('model ', each, ' has no init method')


def initPlugin(f):
    config = f.readlines()
    new = []
    for i in range(0,len(config)):
        if config[i] != '\n':
            path = 'Plugin.' + config[i].replace('\n', '').replace('\\', '.').replace('/', '.')
            new.append(path)
    print(new)
    initModule(new)
    # print(os.getcwd())


def init(window):
    global Window
    Window = window
    log.msg('load plugins---')
    try:
        with open('Plugin/config', 'r', encoding='utf-8') as f:
            initPlugin(f)
    except IOError:
        log.error('load plugins error: No file named config')
        print('没有config文件')






